﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using StuManModels;
using StuManDAL;


namespace StudentManageWinForm
{
    public partial class FrmUserManage : Form
    {
        public FrmUserManage()
        {
            InitializeComponent();
            Init();
        }
        private UserService _service = null;
        private BindingSource _source = null;
        #region 业务逻辑
        private void Init()
        {
            _service = new UserService();
            _source = new BindingSource();
            GetUser();
            dgvUserInfo.AutoGenerateColumns = false;
            dgvUserInfo.DataSource = _source;
        }
        private void GetUser()
        {
            _source.DataSource = _service.GetAllUser();
        }
        private void AddUser()
        {
            _service.AddUser((SysUser)_source.Current, out string info);
            GetUser();
            MessageBox.Show(info);
        }
        private void DeleteUser()
        {
            int count = dgvUserInfo.SelectedRows.Count;
            if (count>0)
            {
               DialogResult result= MessageBox.Show($"确定删除这{count}个用户么?","提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
                if (result==DialogResult.Cancel)
                {
                    return;
                }
                for (int i = 0; i < count; i++)
                {
                    SysUser user = _source.Current as SysUser;
                    int userId = user.UserId;
                    _service.DeleteUser(userId, out string info);
                    _source.Remove(user);
                }
            }
        }
        private void ModifyUser()
        {
            SysUser user = _source.Current as SysUser;
            _service.ModifyUser(user, out string info);
            MessageBox.Show(info);
        }
        #endregion
        #region 事件处理方法
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            AddUser();
        }

        private void btnDelUser_Click(object sender, EventArgs e)
        {
            DeleteUser();
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            ModifyUser();
        }
        #endregion
    }
}
